﻿using System;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;

namespace Hopscotch.Presentation.Common.Converters
{
	/// <summary>
	/// Validation.Errors collection to string value converter
	/// </summary>
	/// <remarks>This needs to be a MultiValueConverter to get around a WPF limitation
	/// where only the first error is shown in a Validation.Errors collection</remarks>
	/// <see cref="http://www.wpftutorial.net/DataValidation.html"/>
	/// <seealso cref="http://connect.microsoft.com/VisualStudio/feedback/details/785207/wpf-validation-does-only-show-the-first-element-from-inotifydataerrorinfo-geterrors"/>
	[ValueConversion(typeof(ReadOnlyObservableCollection<ValidationError>), typeof(string))]
	public class ValidationErrorsToStringConverter : MarkupExtension, IMultiValueConverter
	{
		public override object ProvideValue(IServiceProvider serviceProvider)
		{
			return this;
		}

		public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
		{
			if (values.Length < 1)
				return values;

			var errors = values[0] as ReadOnlyObservableCollection<ValidationError>;

			if (errors == null)
			{
				return string.Empty;
			}
			var query = errors.Where(e => e.ErrorContent != null).Select(p => p.ErrorContent);
			return string.Join(Environment.NewLine, query);
		}

		public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
		{
			throw new NotImplementedException();
		}
	}

}
